<?php
/**
 * Created by PhpStorm.
 * User: xuho
 * Date: 2019-09-04
 * Time: 15:16
 */

namespace extend\notify;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Sms
{
    protected $config = [];

    public function __construct()
    {
        $this->config = [
            'accessKeyId' => config('ali.accessKeyId'),
            'accessKeySecret' => config('ali.accessSecret'),
        ];
    }

    public function aLiDaYu($mobile, $templateCode, $template = [])
    {
        $config = $this->config;
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                //->scheme('https') //https | http（如果域名是https，这里记得开启）
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => config('ali.smsSignName'),
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => json_encode($template, JSON_UNESCAPED_UNICODE),
                    ],
                ])
                ->request();

            $response = $result->toArray();

            if ($response['Code'] == 'OK') {
                return true;
            } else {
                return $response['Message'];
            }
        } catch (ClientException $e) {
            return $e->getErrorMessage();
        } catch (ServerException $e) {
            return $e->getErrorMessage();
        }
    }
}